package com.wjerp.tplus.server.api.controller.base;

import com.wjerp.tplus.server.common.constant.ErrorDetail;
import com.wjerp.tplus.server.common.exception.BusinessException;
import com.wjerp.tplus.server.common.model.BaseResponseData;
import com.wjerp.tplus.server.common.security.JwtUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.Date;


/**
 * The Class BaseController.
 */
public class BaseController {
	
	/** The logger. */
	public static Logger logger = LoggerFactory.getLogger(BaseController.class);


	protected String getUserDisplayId() throws BusinessException {
		JwtUser jwtUser = getCurrentLoginUserInfo();
		if(jwtUser!=null){
			return jwtUser.getDisplayUserId();
		}
		throw new BusinessException(ErrorDetail.USER_NOT_FOUND);
	}

	/**
	 * Fail.
	 *
	 * @param errorCode the error code
	 * @param message the message
	 * @param data the data
	 * @return the response entity
	 */
	protected ResponseEntity<BaseResponseData> fail(String errorCode, String message, Object data) {
		logger.info("REST API business failure: "+ errorCode + ", " + message, data);
		BaseResponseData responseData = new BaseResponseData(errorCode, message, data);
		return new ResponseEntity<BaseResponseData>(responseData, HttpStatus.OK);
	}
	
	/**
	 * Success.
	 *
	 * @param data the data
	 * @return the response entity
	 */
	protected ResponseEntity<BaseResponseData> success(Object data) {
		if(data!=null){
			logger.info("REST API response: " + data.toString());
		}else{
			logger.info("REST API response: Empty Response.");
		}
	
		BaseResponseData responseData = new BaseResponseData(data);
		return new ResponseEntity<BaseResponseData>(responseData, HttpStatus.OK);
	}
	
	/**
	 * Error.
	 *
	 * @param errorCode the error code
	 * @param message the message
	 * @param data the data
	 * @return the response entity
	 */
	protected ResponseEntity<BaseResponseData> error(String errorCode, String message, Object data) {
		logger.error("REST API critical failure: "+ errorCode + ", " + message, data);
		BaseResponseData responseData = new BaseResponseData(errorCode, message, data);
		return new ResponseEntity<BaseResponseData>(responseData, HttpStatus.INTERNAL_SERVER_ERROR);
	}
	
	/**
	 * Timeout.
	 *
	 * @param errorCode the error code
	 * @param message the message
	 * @param data the data
	 * @return the response entity
	 */
	protected ResponseEntity<BaseResponseData> timeout(String errorCode, String message, Object data) {
		logger.error("REST API timeout:" + errorCode + ", " + message, data);
		BaseResponseData responseData = new BaseResponseData(errorCode, message, data);
		return new ResponseEntity<BaseResponseData>(responseData, HttpStatus.GATEWAY_TIMEOUT);
	}

	/**
	 * 格式化日期.
	 *
	 * @param dateInfo the date info
	 * @param dateType 0：表示开始，1：表示结束
	 * @return the string
	 */
	protected String formatDate(String dateInfo,Integer dateType){
		SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		if(dateInfo==null ||dateInfo.isEmpty() || dateInfo.length()<10){
			if(dateType.intValue() == 0){
				return "1900-01-01";
			}else{
				return simpleDateFormat.format(new Date());
			}
		}else{
			dateInfo=dateInfo.replaceAll("\"","");
			dateInfo=dateInfo.substring(0,10);
			if(dateType.intValue() == 0){
				return dateInfo;
			}else {
				return  dateInfo+" 23:59:59";
			}
		}
	}


	/**
	 * Replace with star.
	 *
	 * @param original the original
	 * @return the string
	 */
	private String replaceWithStar(String original){
		String hideStr = "";
		String resultStr = "";
		if(original.length()>4){
			hideStr = generateStarStr(original);
			resultStr = original.substring(0,2)+hideStr+original.substring(original.length()-2,original.length());
		} else{
			resultStr = original;
		}
		return resultStr;
	}

	/**
	 * Generate star str.
	 *
	 * @param original the original
	 * @return the string
	 */
	private String generateStarStr(String original) {
		StringBuilder sb  = new StringBuilder("");
		for(int i=0;i<original.length()-4;i++){
			sb.append("*");
		}
		return sb.toString();
	}

	protected void varifyParams(String[] params) throws BusinessException {
		logger.info("请求参数={}", params);
		for(String param : params){
			if(StringUtils.isEmpty(param)){
				throw new BusinessException(ErrorDetail.REQ_BADLY_SET_ERROR_GENERAL);
			}
		}
	}

	/**
	 * 获取当前登录用户信息
	 * @return 当前登录用户
	 */
	protected  JwtUser getCurrentLoginUserInfo(){
		JwtUser authentication = (JwtUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		return  authentication;
	}


}
